const connection = require('../app/database');
const { formatTimestamp } = require('../utils/common');

class OrderService {
  // 获取订单列表
  async getOrderList(arg) {
    try {
      // 拼接sql语句和传入的data字段
      let dataArr = [], sql = '';
      for (let key in arg) {
        if (!['page', 'size', 'startTime', 'endTime'].includes(key)) { // 首先排除需要处理的字段
          if (arg[key] !== '') { // 当字段为空时，不进行拼接
            sql += `AND ${key} = ? `;
            dataArr.push(arg[key]);
          }
        }
      }
      // 如果传了起始时间和终止时间则进行处理拼接进sql查询语句
      if (arg['startTime'] && arg['endTime']) {
        sql += `AND createTime > ? AND createTime < ?`;
        dataArr.push(formatTimestamp(arg['startTime']));
        dataArr.push(formatTimestamp(arg['endTime']));
      }
      dataArr.push(arg['page']);
      dataArr.push(arg['size']);

      // 拼接sql语句
      const statement = `
        SELECT
        o.id, o.orderNumber, o.desc, o.createTime, o.serverTime, o.finishTime, o.finalPrice, o.evaluation, o.status,
        JSON_OBJECT('id', u.id, 'name', u.name, 'userIdentify', u.identify, 'userPhone', u.phone, 'userAddress', u.address) userInfo,
        JSON_OBJECT('id', w.id, 'name', w.name, 'workerIdentify', w.identify, 'workerPhone', w.phone, 'repairType', w.repairType) workerInfo
        FROM orderList o
        LEFT JOIN user u ON o.user_id = u.id
        LEFT JOIN worker w ON o.worker_id = w.id
        WHERE 1=1 ${sql}
        LIMIT ?, ?;
      `;
      const [result] = await connection.execute(statement, dataArr);
      console.log('[order.service_getOrderList]{success}', result);
      return result;
    } catch (e) {
      console.log('[order.service_getOrderList]{fail}', e);
    }
  }

  // 获取订单总数
  async getOrderCount(arg) {
    try {
      let dataArr = [], sql = '';
      for (let key in arg) {
        if (!['page', 'size', 'startTime', 'endTime'].includes(key)) {
          if (arg[key] !== '') {
            sql += `AND ${key} = ? `;
            dataArr.push(arg[key]);
          }
        }
      }
      if (arg['startTime'] && arg['endTime']) {
        sql += `AND createTime > ? AND createTime < ?`;
        dataArr.push(formatTimestamp(arg['startTime']));
        dataArr.push(formatTimestamp(arg['endTime']));
      }

      const statement = `
        SELECT COUNT(*) total FROM orderList WHERE 1=1 ${sql};
      `;
      const [result] = await connection.execute(statement, dataArr);
      console.log('[order.service_getOrderCount]{success}', result);
      return result[0]['total'];
    } catch (e) {
      console.log('[order.service_getOrderList]{fail}', e);
    }
  }

  // 修改订单状态status
  async editOrderStatus(arg) {
    try {
      const statement = `
        UPDATE orderList SET status = ? WHERE id = ?;
      `;
      const [result] = await connection.execute(statement, [arg.status, arg.id]);
      console.log('[order.service_editOrderStatus]{success}', result);
      return true;
    } catch(e) {
      console.log('[order.service_editOrderStatus]{fail}', e);
    }
  }
}

module.exports = new OrderService();